import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Login from '../views/Login.vue'
import Admin from '../views/Admin.vue'
import Notice from '../views/Notice.vue'
import Student from '../views/Student.vue'
import Shownotice from '../views/Shownotice.vue'
import Hotel from '../views/Hotel.vue'
import A404 from '../views/404.vue'
Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: Login,
  },
  {
    path: '/home',
    name: 'home',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    components: {
      default: Home
    },
    children: [
      {
        path: 'shownotice',
        name: 'shownotice',
        component: Shownotice,
        meta: {
          title: ['公告主页'],
          role: ['2'],
          nav: true
        }
      },
      {
        path: 'hotel',
        name: 'hotel',
        component: Hotel,
        meta: {
          title: ['宿舍管理'],
          role: ['2'],
          nav: true
        }
      },
      {
        path: 'student',
        name: 'student',
        component: Student,
        meta: {
          title: ['学生管理'],
          role: ['2', '1'],
          nav: true
        }
      },
      {
        path: 'notice',
        name: 'notice',
        component: Notice,
        meta: {
          title: ['公告管理'],
          role: ['2'],
          nav: true
        }
      },
      {
        path: 'admin',
        name: 'admin',
        component: Admin,
        meta: {
          title: ['管理员管理'],
          role: ['2'],
          nav: true
        }
      }
    ],
  },
  {
    path: '404',
    name: '404',
    component: A404,
  }
]
const router = new VueRouter({
  routes,
  mode: 'history',
});

// const role = 'user'
// router.beforeEach((to, from, next) => {
//   if (to.matched.some(record => record.meta.nav)) {
//     next()
//   } else {
//     next({ path: '/404' })
//   }
// });

router.beforeEach((to, from, next) => {
  // 如果有token 说明该用户已登陆
  let token = localStorage.getItem('token');
  if (token) {
    //如果用户信息存在则往下执行。
    next()
  } else {
    //如果用户token不存在则跳转到login页面
    if (to.path === '/login') {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
    }
  }
})

// const originalPush = VueRouter.prototype.push
// VueRouter.prototype.push = function push (location, onResolve, onReject) {
//   if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
//   return originalPush.call(this, location).catch(err => err)
// }
export default router
